﻿using DocumentFormat.OpenXml.Office2021.DocumentTasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.Common;
using NP.BPMReportPlatform.Contract.Dtos;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.RecurringJobs;
using NP.BPMReportPlatform.Utils;
using NP.Enterprise.Utils.Http;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using static NP.BPMReportPlatform.Contract.Dtos.ContractEnum;

namespace NP.BPMReportPlatform.Contract
{
    /// <summary>
    /// 合同状态服务（底层，这里只能被引入，不要引入ContractService,ESignService）
    /// </summary>
    public class ContractStatusService : BPMReportPlatformAppService
    {
        private readonly SqlSugarClient _dbContext;
        private readonly SqlSugarClient _dbPlatform;
        private readonly ISFSyncJob _sFSyncJob;
        private readonly ICommonService _commonService;

        public ContractStatusService(ISqlSugarAppService sqlSugarAppService, ISFSyncJob sFSyncJob
            , IBPMPlatformAppService iBPMPlatformApp, INPRestHttpHelper nPRestHttp, ICommonService commonService)
        {
            _dbContext = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _sFSyncJob = sFSyncJob;
            _commonService = commonService;
        }

        /// <summary>
        /// 合同状态更新
        /// </summary>
        /// <param name="contractCode">合同编号</param>
        /// <param name="status">状态</param>
        public void UpdateContractStatus(string contractCode, ContractStatusEnum status)
        {
            var contract = _dbPlatform.Queryable<UserContractEntity>().First(t => t.ContractCode == contractCode || t.ContractId == contractCode);
            if (contract == null)
            {
                return;
            }

            int oldStatus = contract.ContractStatus ?? 0;

            contract.ContractStatus = status.GetHashCode();
            contract.ContractStatusName = status.ToString();

            switch (status)
            {
                case ContractStatusEnum.未生效:
                    if (!contract.ParentContractCode.IsNullOrEmpty())
                    {
                        UpdateContractRenewalStatus(contract.ParentContractCode, ContractRenewalStatusEnum.已续签);
                    }
                    break;
                case ContractStatusEnum.签署中:
                    if (!contract.ParentContractCode.IsNullOrEmpty())
                    {
                        UpdateContractRenewalStatus(contract.ParentContractCode, ContractRenewalStatusEnum.签署中);
                    }
                    break;
                case ContractStatusEnum.作废中:
                    break;
                case ContractStatusEnum.已作废:
                    // 发送邮件--电子签
                    if (!string.IsNullOrEmpty(contract.SignFlowId) && oldStatus == ContractStatusEnum.作废中.GetHashCode())
                    {
                        _commonService.SendEmail(ContractEmailTypeEnum.合同电子签签署作废,
                            $"{contract.UserName}({contract.WorkNumber})", contract.CreateUserWorkNumber, contract.ContractCode);
                    }
                    contract.ContractCode = contract.ContractCode + "_S";

                    // 如果是续签作废，则原合同需要还能续签
                    if (!contract.ParentContractCode.IsNullOrEmpty())
                    {
                        var parentContract = _dbPlatform.Queryable<UserContractEntity>().Where(t => t.ContractCode == contract.ParentContractCode).First();
                        if (parentContract != null)
                        {
                            parentContract.ContractRenewalStatus = null;
                            parentContract.ContractRenewalStatusName = "已作废";
                            _dbPlatform.Updateable(parentContract).UpdateColumns(t => new { t.ContractRenewalStatus, t.ContractRenewalStatusName }).ExecuteCommand();
                        }
                    }
                    break;
                case ContractStatusEnum.已终止:
                    break;
                case ContractStatusEnum.履行中:
                    // 发送邮件--电子签
                    if (!string.IsNullOrEmpty(contract.SignFlowId) && oldStatus == ContractStatusEnum.签署中.GetHashCode())
                    {
                        _commonService.SendEmail(ContractEmailTypeEnum.合同电子签签署完成,
                            $"{contract.UserName}({contract.WorkNumber})", contract.CreateUserWorkNumber, contract.ContractCode);
                    }

                    // 判断日期是否到了
                    if (contract.ContractStartDate > DateTime.Now)
                    {
                        contract.ContractStatus = ContractStatusEnum.未生效.GetHashCode();
                        contract.ContractStatusName = ContractStatusEnum.未生效.ToString();
                    }
                    else
                    {
                        // 此处应该推送SF
                        _sFSyncJob.PushContractToSF(contract.ContractCode);

                        // 如果是退休返聘，将历史履行中的合同更改为已终止
                        if (contract.ContractCode.IndexOf("FP") > -1)
                        {
                            var oldcontract = _dbPlatform.Queryable<UserContractEntity>().Where(t => t.ContractStatus == ContractStatusEnum.履行中.GetHashCode() && t.WorkNumber == contract.WorkNumber).First();
                            if (oldcontract != null)
                            {
                                UpdateContractStatus(oldcontract.ContractCode, ContractStatusEnum.已终止);
                            }
                        }
                    }
                    if (!contract.ParentContractCode.IsNullOrEmpty())
                    {
                        UpdateContractRenewalStatus(contract.ParentContractCode, ContractRenewalStatusEnum.已续签);
                    }
                    break;
                default: break;
            }
            _dbPlatform.Updateable(contract).UpdateColumns(t => new { t.ContractStatus, t.ContractStatusName, t.ContractCode }).ExecuteCommand();
        }

        /// <summary>
        /// 合同三方变更状态更新
        /// </summary>
        /// <param name="contractCode">合同编号</param>
        /// <param name="status">状态</param>
        public void UpdateChangeContractStatus(string changeContractCode, ContractChangeStatusEnum status)
        {
            var contract = _dbPlatform.Queryable<UserContractTripartiteAgreementEntity>()
                .First(t => t.ChangeContractCode == changeContractCode || t.Id == changeContractCode);
            if (contract == null)
            {
                return;
            }
            contract.ChangeStatus = status.GetHashCode();
            contract.ChangeStatusName = status.ToString();

            switch (status)
            {
                case ContractChangeStatusEnum.签署中:
                    break;
                case ContractChangeStatusEnum.作废中:
                    break;
                case ContractChangeStatusEnum.签署失败:
                    break;
                case ContractChangeStatusEnum.已作废:
                    // 发送邮件--电子签
                    if (!string.IsNullOrEmpty(contract.SignFlowId))
                    {
                        _commonService.SendEmail(ContractEmailTypeEnum.主体变更协议电子签签署作废,
                             contract.PartyBName, contract.CreateWorkNumber, contract.ChangeContractCode);
                    }
                    break;
                case ContractChangeStatusEnum.签署成功:
                    // 此处应该推送SF
                    _sFSyncJob.PushContractChangeToSF(contract.ChangeContractCode);
                    // 发送邮件--电子签
                    if (!string.IsNullOrEmpty(contract.SignFlowId))
                    {
                        _commonService.SendEmail(ContractEmailTypeEnum.主体变更协议电子签签署完成,
                            contract.PartyBName, contract.CreateWorkNumber, contract.ChangeContractCode);
                    }
                    break;
                default: break;
            }
            _dbPlatform.Updateable(contract).UpdateColumns(t => new { t.ChangeStatus, t.ChangeStatusName }).ExecuteCommand();
        }

        /// <summary>
        /// 合同续签状态更新(跟随合同，请不要在服务外面调用)
        /// </summary>
        /// <param name="contractCode">合同编号</param>
        /// <param name="status">状态</param>
        private void UpdateContractRenewalStatus(string contractCode, ContractRenewalStatusEnum status)
        {
            var contract = _dbPlatform.Queryable<UserContractEntity>().First(t => t.ContractCode == contractCode || t.ContractId == contractCode);
            if (contract == null)
            {
                return;
            }
            contract.ContractRenewalStatus = status.GetHashCode();
            contract.ContractRenewalStatusName = status.ToString();

            switch (status)
            {
                case ContractEnum.ContractRenewalStatusEnum.未生效:
                case ContractEnum.ContractRenewalStatusEnum.签署中:
                    break;
                case ContractEnum.ContractRenewalStatusEnum.已续签:
                    break;
                default: break;
            }

            _dbPlatform.Updateable(contract).UpdateColumns(t => new { t.ContractRenewalStatus, t.ContractRenewalStatusName }).ExecuteCommand();
        }
    }
}
